package www.zengzhuo.cn.mac.launch;

import www.zengzhuo.cn.mac.enums.LaunchType;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class LaunchScan {

    public static List<LaunchPList> scan(String name, LaunchType... launchTypes) {
        List<LaunchPList> launchPLists = new ArrayList<>();
        for (LaunchType launchType : launchTypes) {
            File root = new File(launchType.getPath());
            if (root.exists()) {
                File[] plists = root.listFiles(new FileNameFilter(name));
                if (plists != null) {
                    for (File plist : plists) {
                        launchPLists.add(new LaunchPList(plist, launchType));
                    }
                }
            }
        }
        return launchPLists;
    }

    static class FileNameFilter implements FilenameFilter {
        private Pattern pattern = null;;

        public FileNameFilter(String name) {
            if (name != null) {
                pattern = Pattern.compile(name);
            }
        }

        @Override
        public boolean accept(File dir, String name) {
            if (!name.endsWith(".plist")) {
                return false;
            }
            if (pattern != null) {
                return pattern.matcher(name).matches();
            }
            return true;
        }
    }
}
